﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Zj.CourseManage.Domain.Core;
using Zj.CourseManage.Mvc.Models;
using Zj.CourseManage.DTO.Common.Pagination;
using Zj.CourseManage.DTO.Common;
using Microsoft.AspNetCore.Mvc.Rendering;

namespace Zj.CourseManage.Mvc.Controllers
{
    public class TeachersController : Controller
    {
        private readonly DbContext _ctx;
        public TeachersController(DbContext ctx)
        {
            this._ctx = ctx;
        }
        // GET: Teachers
        public ActionResult Index(int pageIndex = 1, int pageSize = 3, string sortField = "", string searchString = "")
        {
            var entities = _ctx.Set<Teacher>().AsQueryable();
            if (!string.IsNullOrEmpty(searchString))
            {
                entities = entities.Where(t => t.Name.Contains(searchString));
            }
            switch (sortField)
            {
                case "idDesc":
                    entities = entities.OrderByDescending(t => t.Id);
                    break;
                case "nameDesc":
                    entities = entities.OrderByDescending(t => t.Name);
                    break;
                case "name":
                    entities = entities.OrderBy(t => t.Name);
                    break;
                case "hireDateDesc":
                    entities = entities.OrderByDescending(t => t.HireDate);
                    break;
                case "hireDate":
                    entities = entities.OrderBy(t => t.HireDate);
                    break;
                default:
                    entities = entities.OrderBy(t => t.Id);
                    break;
            }
            ViewData["pageIndex"] = pageIndex;
            ViewData["sortId"] = sortField.Equals("") ? "idDesc" : "";
            ViewData["sortName"] = sortField.Equals("nameDesc") ? "name" : "nameDesc";
            ViewData["sortHireDate"] = sortField.Equals("hireDateDesc") ? "hireDate" : "hireDateDesc";
            ViewData["searchString"] = searchString;
            var dtos = entities.Select(t => new TeacherVm() { Id = t.Id, Name = t.Name, HireDate = t.HireDate, Office = t.Office, Couses = t.CourseAssignments.Select(c => c.Course).ToList() }).AsNoTracking();
            var list = PaginatedList<TeacherVm>.CreatePaging(dtos, pageIndex, pageSize);

            return View(list);
        }

        // GET: Teachers/Details/5
        public ActionResult Details(int id)
        {
            return View();
        }

        // GET: Teachers/Create
        public async Task<ActionResult> Create()
        {

            ViewData["offices"] =await PopularOfficeDropdownListAsync();
            return View();
        }

        // POST: Teachers/Create
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Create(TeacherDTO dto)
        {
            try
            {
                var entity = new Teacher() { Name = dto.Name, HireDate = dto.HireDate, OfficeId = dto.OfficeId };
                // TODO: Add insert logic here
                _ctx.Add(entity);
                await _ctx.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            catch
            {
                return View();
            }
        }

        // GET: Teachers/Edit/5
        public ActionResult Edit(int id)
        {
            return View();
        }

        // POST: Teachers/Edit/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(int id, IFormCollection collection)
        {
            try
            {
                // TODO: Add update logic here

                return RedirectToAction(nameof(Index));
            }
            catch
            {
                return View();
            }
        }

        public async Task<ActionResult> Delete(int? id)
        {
            try
            {
                if (id == null)
                {
                    return NotFound();
                }
                var entity = await _ctx.Set<Teacher>().SingleOrDefaultAsync(t => t.Id == id);
                // TODO: Add delete logic here
                if (entity == null)
                {
                    return NotFound();
                }
                _ctx.Remove(entity);
                await _ctx.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            catch
            {
                return View();
            }
        }



        /// <summary>
        /// office data fill  the dropdownlist
        /// </summary>
        /// <param name="selectItem"></param>
        /// <returns></returns>
        private async Task<SelectList> PopularOfficeDropdownListAsync(object selectItem = null)
        {
            var items = await _ctx.Set<Office>().Select(o => new { Id = o.Id, Name = o.Name }).ToListAsync();
            return new SelectList(items, "Id", "Name", selectItem);
        }
    }
}